package Sdo.application;

import Sdo.pojo.History;
import Sdo.pojo.PFile;
import Sdo.sftp.FileViewfx;
import Sdo.sftp.JschTools;
import Sdo.terminalfx.TerminalBuilder;
import Sdo.terminalfx.TerminalTab;
import Sdo.terminalfx.config.TerminalConfig;
import Sdo.terminalfx.helper.ThreadHelper;
import Sdo.util.SqliteUtil;
import Sdo.util.addPane;
import Sdo.util.editPane;
import de.codecentric.centerdevice.MenuToolkit;
import de.codecentric.centerdevice.dialogs.about.AboutStageBuilder;
import de.codecentric.centerdevice.icns.IcnsParser;
import de.codecentric.centerdevice.icns.IcnsType;
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import org.apache.commons.lang3.SystemUtils;
import org.apache.log4j.Logger;
import org.controlsfx.control.Notifications;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

public class Main extends Application {
	private static Logger logger = Logger.getLogger(Main.class);

	// ResourceBundle bundle = ResourceBundle.getBundle("language.shell",
	// Locale.CHINA);
	private TabPane mtabs;
	TableView<History> table;
	ObservableList<History> data = FXCollections.observableArrayList();
	//设置图标
	Image icon =new Image(getClass().getResourceAsStream("/icon.png"));

	Image iconimage =new Image("/icon.png", 20, 20, false, false);
	
	//ImageView iconimage = new ImageView(new Image("/icon.png", 20, 20, false, false));
	
	
	
	Tab tab = new Tab();
	public void opensftp(History history) {
		ThreadHelper.start(() -> {
			ThreadHelper.runActionLater(() -> {
				FileViewfx tab1;
				try {

					tab1 = new FileViewfx(history);
					
					tab1.setText( "■"+history.getName());
					
					tab1.setId("" + history.getId());
					mtabs.getTabs().add(tab1);
					mtabs.getSelectionModel().select(tab1);// 默认选中

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

				}
			});

		});
	}

	
	
	@Override
	public void start(Stage primaryStage) {
//		logger.debug("开始");

		BorderPane root = new BorderPane();
		mtabs = new TabPane();
		try {
			newtab();
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		tab.setText("主机列表");
		tab.setClosable(false);
		tab.setId("mainlist");
		mtabs.getTabs().add(tab);
		mtabs.getSelectionModel().select(tab);// 默认选中

		mtabs.prefWidthProperty().bind(root.widthProperty());
		mtabs.prefHeightProperty().bind(root.heightProperty());

		root.setCenter(mtabs);

		Scene scene = new Scene(root, 800, 600);

		try {
			primaryStage.getIcons().add(icon);

		} catch (Exception e) {
			// TODO: handle exception
			logger.debug(e.getMessage());
		}

		WinAndLiunxMainTableInit(root);

		primaryStage.setScene(scene);
		primaryStage.show();
		ThreadHelper.runActionLater(() -> {

			try {

				if (SystemUtils.IS_OS_MAC_OSX) {
					MainTableInit(primaryStage);
				} else {
					WinAndLiunxMainTableInit(root);
				}

			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				logger.error("获取数据异常" + e1.getMessage());
				e1.printStackTrace();
			}

		});

		primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {

			@Override
			public void handle(WindowEvent event) {
				// TODO Auto-generated method stub
				// primaryStage.close();
				Platform.exit();
				System.exit(0);
			}
		});

	}

	private void WinAndLiunxMainTableInit(BorderPane root) {
		// TODO Auto-generated method stub
		HBox vbox = new HBox();
		Image btnadd = new Image("/icon/btnadd.png", 50, 50, false, false);
		Button newbtn = new Button("",new ImageView(btnadd));//新建主机
	
		newbtn.setPrefWidth(50);
		newbtn.setPrefHeight(50);
		newbtn.setStyle("-fx-padding: 0");
		newbtn.setStyle("-fx-background-insets: 0");//去除边框样式
	        
	        
		//Image btnsh = new Image("/icon/btnsh.png", 50, 50, false, false);
		Image btnssh = new Image("/icon/btnshell.png", 50, 50, false, false);
		Button opensshBtn = new Button("",new ImageView(btnssh));//打开SSH
		
		
		opensshBtn.setPrefWidth(50);
		opensshBtn.setPrefHeight(50);
		opensshBtn.setStyle("-fx-padding: 0");
		opensshBtn.setStyle("-fx-background-insets: 0");//去除边框样式
	        
		Image btnftp = new Image("/icon/btnftp.png", 50, 50, false, false);
		Button opensftpBtn = new Button("",new ImageView(btnftp));//打开SFTP
		
		opensftpBtn.setPrefWidth(50);
		opensftpBtn.setPrefHeight(50);
		opensftpBtn.setStyle("-fx-padding: 0");
		opensftpBtn.setStyle("-fx-background-insets: 0");//去除边框样式
	        
		opensshBtn.setDisable(true);
		opensftpBtn.setDisable(true);

		
//		Image btnm = new Image("/icon.png", 50, 50, false, false);
//		Button openshellBtn = new Button("",new ImageView(btnm));//打开终端
//		
		vbox.getChildren().addAll(newbtn, opensshBtn, opensftpBtn);

		mtabs.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {
			@Override
			public void changed(ObservableValue<? extends Tab> ov, Tab t, Tab t1) {
				String selectone = mtabs.getSelectionModel().getSelectedItem().getId();
				if (mtabs.getSelectionModel().getSelectedItem() == null) {

				} else {
					if (selectone.equals("mainlist")) {
						opensshBtn.setDisable(true);
						opensftpBtn.setDisable(true);

					} else if (selectone.equals("mainshell")) {

						opensshBtn.setDisable(true);
						opensftpBtn.setDisable(true);

					} else {
						opensshBtn.setDisable(false);
						opensftpBtn.setDisable(false);

					}
				}
			}
		});

		root.setTop(vbox);

		opensshBtn.setOnAction(e -> {

			// 获取当前选中的TAB的ID
			String selectone = mtabs.getSelectionModel().getSelectedItem().getId();
			SqliteUtil sq = new SqliteUtil();
			ResultSet rSet;
			try {
				rSet = sq.queryById("history", Integer.parseInt(selectone));

				History shistory = new History(Integer.parseInt(rSet.getString("id")), rSet.getString("name"),
						rSet.getString("ip"), Integer.parseInt(rSet.getString("port")), rSet.getString("username"),
						rSet.getString("password"), rSet.getString("pkey"), rSet.getString("proxytype"),
						rSet.getString("proxyip"), rSet.getString("proxyport"), rSet.getString("proxyuser"),
						rSet.getString("proxypassword"),new ImageView(iconimage));
				openSsh(shistory);
				// openSsh(shistory);
			} catch (NumberFormatException e1) {
				// TODO Auto-generated catch block

				ThreadHelper.runActionLater(() -> {
					Notifications noca = Notifications.create().title("服务器链接失败").text(e1.getMessage()).graphic(null)
							.hideAfter(Duration.seconds(3)).position(Pos.TOP_RIGHT)
							.onAction(new EventHandler<ActionEvent>() {
								@Override
								public void handle(ActionEvent event) {
									// TODO Auto-generated method stub
									System.out.println("test");
								}
							});
					noca.showConfirm();

				});

				// e1.printStackTrace();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				ThreadHelper.runActionLater(() -> {
					Notifications noca = Notifications.create().title("获取服务器信息失败").text(e1.getMessage()).graphic(null)
							.hideAfter(Duration.seconds(3)).position(Pos.TOP_RIGHT)
							.onAction(new EventHandler<ActionEvent>() {
								@Override
								public void handle(ActionEvent event) {
									// TODO Auto-generated method stub
									System.out.println("test");
								}
							});
					noca.showConfirm();

				});
				// e1.printStackTrace();
			}
		});

		opensftpBtn.setOnAction(e -> {
			ThreadHelper.start(() -> {
				ThreadHelper.runActionLater(() -> {

					// 获取当前选中的TAB的ID
					String selectone = mtabs.getSelectionModel().getSelectedItem().getId();
					SqliteUtil sq = new SqliteUtil();
					ResultSet rSet;
					try {
						rSet = sq.queryById("history", Integer.parseInt(selectone));
						History thistory = new History(Integer.parseInt(rSet.getString("id")), rSet.getString("name"),
								rSet.getString("ip"), Integer.parseInt(rSet.getString("port")),
								rSet.getString("username"), rSet.getString("password"), rSet.getString("pkey"),
								rSet.getString("proxytype"), rSet.getString("proxyip"), rSet.getString("proxyport"),
								rSet.getString("proxyuser"), rSet.getString("proxypassword"),new ImageView(iconimage));

						opensftp(thistory);
					} catch (NumberFormatException e1) {
						// TODO Auto-generated catch block
						logger.error("数据转换异常" + e1.getMessage());
						e1.printStackTrace();
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						logger.error("获取数据异常" + e1.getMessage());
						e1.printStackTrace();
					}
				});

			});
		});

//		openshellBtn.setOnAction(e -> {
//			ThreadHelper.start(() -> {
//				ThreadHelper.runActionLater(() -> {
//					TerminalConfig darkConfig = new TerminalConfig();
//					darkConfig.setBackgroundColor(Color.rgb(16, 16, 16));
//					darkConfig.setForegroundColor(Color.rgb(240, 240, 240));
//					darkConfig.setCursorColor(Color.rgb(255, 0, 0, 0.5));
//
//					TerminalBuilder terminalBuilder = new TerminalBuilder(darkConfig);
//					TerminalTab terminal = terminalBuilder.newTerminal(new BorderPane());
//
//					terminal.setText("SdoShell");
//					terminal.setId("mainshell");
//					mtabs.getTabs().add(terminal);
//					mtabs.getSelectionModel().select(terminal);// 默认选中
//				});
//
//			});
//		});

		newbtn.setOnAction(e -> {
			ThreadHelper.start(() -> {
				ThreadHelper.runActionLater(() -> {
					try {
						add();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						logger.error("创建添加异常" + e1.getMessage());
						e1.printStackTrace();

					}
				});

			});
		});

	}

	public void MainTableInit(Stage primaryStage) throws SQLException {

		MenuToolkit tk = MenuToolkit.toolkit();

		Menu defaultApplicationMenu = tk.createDefaultApplicationMenu("SdoShell");

		defaultApplicationMenu.getItems().get(1).setText("Hide all the otters");

		AboutStageBuilder aboutStageBuilder = AboutStageBuilder.start("SdoShell").withAppName("SdoShell")
				.withCloseOnFocusLoss().withHtml("<i>版本:个人免费版<br/>网址:http://www.Sdo.gs<br/>作者:http://www.kwor.cn</i>")
				.withVersionString("Version 1.1")
				.withCopyright("Copyright \u00A9 " + Calendar.getInstance().get(Calendar.YEAR));

		try {
			IcnsParser parser = IcnsParser.forFile(AboutStageBuilder.DEFAULT_APP_ICON);
			aboutStageBuilder = aboutStageBuilder.withImage(new Image(parser.getIconStream(IcnsType.ic08)));
		} catch (IOException e) {
			// Too bad, cannot load dummy image
		}

		Menu applicationMenu = tk.createDefaultApplicationMenu("SdoShell", aboutStageBuilder.build());

		// MenuBar bar = new MenuBar();

		tk.setApplicationMenu(defaultApplicationMenu);

		MenuBar bar = new MenuBar();

		MenuItem item1 = new MenuItem("检测更新");
		MenuItem item2 = new MenuItem("帮助");
		MenuItem item3 = new MenuItem("官方网站");
		MenuItem item4 = new MenuItem("作者网站");

		MenuItem newbtn = new MenuItem("新建");
		MenuItem openshellBtn = new MenuItem("打开终端");
//		MenuItem opensftpBtn = new MenuItem("打开SFTP");
//		MenuItem opensshBtn = new MenuItem("打开SSH");

		Menu runmenu = new Menu("运行");
		runmenu.getItems().addAll(newbtn, openshellBtn);

		Menu menu1 = new Menu("设置");
		menu1.getItems().addAll(item1, item2, item3, item4);

		bar.getMenus().addAll(applicationMenu, runmenu, menu1);

		tk.setMenuBar(primaryStage, bar);
		tk.setMenuBar(bar);

//		opensshBtn.setOnAction(e -> {
//
//			// 获取当前选中的TAB的ID
//			String selectone = mtabs.getSelectionModel().getSelectedItem().getId();
//
//			SqliteUtil sq = new SqliteUtil();
//			ResultSet rSet;
//			try {
//				rSet = sq.queryById("history", Integer.parseInt(selectone));
//
//				History shistory = new History(Integer.parseInt(rSet.getString("id")), rSet.getString("name"),
//						rSet.getString("ip"), Integer.parseInt(rSet.getString("port")), rSet.getString("username"),
//						rSet.getString("password"), rSet.getString("pkey"), rSet.getString("proxytype"),
//						rSet.getString("proxyip"), rSet.getString("proxyport"), rSet.getString("proxyuser"),
//						rSet.getString("proxypassword"));
//				openSsh(shistory);
//				// openSsh(shistory);
//			} catch (NumberFormatException e1) {
//				// TODO Auto-generated catch block
//
//				ThreadHelper.runActionLater(() -> {
//					Notifications noca = Notifications.create().title("服务器链接失败").text(e1.getMessage()).graphic(null)
//							.hideAfter(Duration.seconds(3)).position(Pos.TOP_RIGHT)
//							.onAction(new EventHandler<ActionEvent>() {
//								@Override
//								public void handle(ActionEvent event) {
//									// TODO Auto-generated method stub
//									System.out.println("test");
//								}
//							});
//					noca.showConfirm();
//
//				});
//
//				// e1.printStackTrace();
//			} catch (SQLException e1) {
//				// TODO Auto-generated catch block
//				ThreadHelper.runActionLater(() -> {
//					Notifications noca = Notifications.create().title("获取服务器信息失败").text(e1.getMessage()).graphic(null)
//							.hideAfter(Duration.seconds(3)).position(Pos.TOP_RIGHT)
//							.onAction(new EventHandler<ActionEvent>() {
//								@Override
//								public void handle(ActionEvent event) {
//									// TODO Auto-generated method stub
//									System.out.println("test");
//								}
//							});
//					noca.showConfirm();
//
//				});
//				// e1.printStackTrace();
//			}
//		});

//		opensftpBtn.setOnAction(e -> {
//
//			// 获取当前选中的TAB的ID
//			String selectone = mtabs.getSelectionModel().getSelectedItem().getId();
//
//			SqliteUtil sq = new SqliteUtil();
//			ResultSet rSet;
//			try {
//				rSet = sq.queryById("history", Integer.parseInt(selectone));
//				History thistory = new History(Integer.parseInt(rSet.getString("id")), rSet.getString("name"),
//						rSet.getString("ip"), Integer.parseInt(rSet.getString("port")), rSet.getString("username"),
//						rSet.getString("password"), rSet.getString("pkey"), rSet.getString("proxytype"),
//						rSet.getString("proxyip"), rSet.getString("proxyport"), rSet.getString("proxyuser"),
//						rSet.getString("proxypassword"));
//
//				opensftp(thistory);
//			} catch (NumberFormatException e1) {
//				// TODO Auto-generated catch block
//				logger.error("数据转换异常" + e1.getMessage());
//				e1.printStackTrace();
//			} catch (SQLException e1) {
//				// TODO Auto-generated catch block
//				logger.error("获取数据异常" + e1.getMessage());
//				e1.printStackTrace();
//			}
//
//		});

		openshellBtn.setOnAction(e -> {
			TerminalConfig darkConfig = new TerminalConfig();
			darkConfig.setBackgroundColor(Color.rgb(16, 16, 16));
			darkConfig.setForegroundColor(Color.rgb(240, 240, 240));
			darkConfig.setCursorColor(Color.rgb(255, 0, 0, 0.5));

			TerminalBuilder terminalBuilder = new TerminalBuilder(darkConfig);
			TerminalTab terminal = terminalBuilder.newTerminal(new BorderPane());

			terminal.setText("SdoShell");
			terminal.setId("mainshell");
			mtabs.getTabs().add(terminal);
			mtabs.getSelectionModel().select(terminal);// 默认选中
		});

		newbtn.setOnAction(e -> {

			try {
				add();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				logger.error("创建添加异常" + e1.getMessage());
				e1.printStackTrace();

			}

		});

		item1.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				// TODO Auto-generated method stub
				try {
					Desktop.getDesktop().browse(new URI("http://sdo.gs/update/"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		item2.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				// TODO Auto-generated method stub
				try {
					Desktop.getDesktop().browse(new URI("http://sdo.gs/help/"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		item3.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				// TODO Auto-generated method stub
				try {
					Desktop.getDesktop().browse(new URI("http://sdo.gs"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		item4.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				// TODO Auto-generated method stub
				try {
					Desktop.getDesktop().browse(new URI("http://www.kwor.cn"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

	}

	private void newtab() throws SQLException {
		// TODO Auto-generated method stub

		table = new TableView<History>();
		
		TableColumn<History, ImageView> ImageCol = new TableColumn<History, ImageView>("");
		
		TableColumn<History, String> NameCol = new TableColumn<History, String>("名称");
		NameCol.setPrefWidth(200);
		TableColumn<History, String> IpCol = new TableColumn<History, String>("IP");
		IpCol.setPrefWidth(200);
		TableColumn<History, String> PortCol = new TableColumn<History, String>("端口");
		PortCol.setPrefWidth(180);
		TableColumn<History, String> UsernameCol = new TableColumn<History, String>("用户名");
		UsernameCol.setPrefWidth(200);
		NameCol.setCellValueFactory(new PropertyValueFactory<History, String>("name"));
		IpCol.setCellValueFactory(new PropertyValueFactory<History, String>("ip"));

		PortCol.setCellValueFactory(new PropertyValueFactory<History, String>("port"));
		UsernameCol.setCellValueFactory(new PropertyValueFactory<History, String>("username"));

		ImageCol.setCellValueFactory(new PropertyValueFactory<History, ImageView>("image"));
		ImageCol.setStyle("-fx-alignment: CENTER;");
		
		
		table.getColumns().addAll(ImageCol,NameCol, IpCol, PortCol, UsernameCol);

		tableBindAction();// 绑定各种事件
		refersh();
		// table.setItems(data);
		tab.setContent(table);
	}

	public void refersh() throws SQLException {
		// TODO Auto-generated method stub

		data.clear();
		// table = new TableView<History>();

		SqliteUtil sq = new SqliteUtil();
		ResultSet rSet = sq.queryAll("history");

	
		
		while (rSet.next()) {
			
			//System.out.println("sssss"+iconimage);
			History history = new History(rSet.getInt("id"), rSet.getString("name"), rSet.getString("ip"),
					Integer.parseInt(rSet.getString("port")), rSet.getString("username"), rSet.getString("password"),
					rSet.getString("pkey"), rSet.getString("proxytype"), rSet.getString("proxyip"),
					rSet.getString("proxyport"), rSet.getString("proxyuser"), rSet.getString("proxypassword"),new ImageView(iconimage));

			data.add(history);
		}
		// TableViewbindAction();
		table.setItems(data);

	}

	public void tableBindAction() {

		ContextMenu cm = new ContextMenu();
		MenuItem openssh = new MenuItem("SSH");
		cm.getItems().add(openssh);
		MenuItem opensftp = new MenuItem("SFTP");
		cm.getItems().add(opensftp);
		MenuItem edit = new MenuItem("编辑");
		cm.getItems().add(edit);
		MenuItem delete = new MenuItem("删除");
		cm.getItems().add(delete);

		table.setRowFactory(tv -> {
			TableRow<History> row = new TableRow<>();
			row.setOnMouseClicked(new EventHandler<MouseEvent>() {
				@Override
				public void handle(MouseEvent event) {
					if (event.getClickCount() == 2 && (!row.isEmpty())) {
						History rowData = row.getItem();

						openSsh(rowData);

					}

				}
			});

			row.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

				@Override
				public void handle(MouseEvent t) {
					if (t.getButton() == MouseButton.SECONDARY && (!row.isEmpty())) {
						cm.show(table, t.getScreenX(), t.getScreenY());
						History rowData = row.getItem();

						openssh.setOnAction((ActionEvent e) -> {
							openSsh(rowData);
						});
						opensftp.setOnAction((ActionEvent e) -> {

							opensftp(rowData);

						});
						edit.setOnAction((ActionEvent e) -> {
							try {
								edit(rowData);
							} catch (Exception e1) {
								ThreadHelper.runActionLater(() -> {
									Notifications noca = Notifications.create().title("编辑信息失败").text(e1.getMessage())
											.graphic(null).hideAfter(Duration.seconds(3)).position(Pos.TOP_RIGHT)
											.onAction(new EventHandler<ActionEvent>() {
												@Override
												public void handle(ActionEvent event) {
													// TODO Auto-generated method stub
													System.out.println("编辑失败");
													
												}
											});
									noca.showConfirm();

								});
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}

						});

						delete.setOnAction((ActionEvent e) -> {

							try {
								delete(rowData);
							} catch (ClassNotFoundException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							} catch (SQLException e1) {
								logger.debug(e1.getMessage());

								ThreadHelper.runActionLater(() -> {
									Notifications noca = Notifications.create().title("删除失败").text(e1.getMessage())
											.graphic(null).hideAfter(Duration.seconds(3)).position(Pos.TOP_RIGHT)
											.onAction(new EventHandler<ActionEvent>() {
												@Override
												public void handle(ActionEvent event) {
													// TODO Auto-generated method stub
													System.out.println("删除失败");
												}
											});
									noca.showConfirm();

								});
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}

						});

					}
					if (t.getButton() == MouseButton.MIDDLE || t.getButton() == MouseButton.PRIMARY) {
						if (cm.isShowing()) {
							cm.hide();
						}

					}
				}
			});

			return row;
		});

		table.setOnKeyPressed(new EventHandler<KeyEvent>() {

			@Override
			public void handle(KeyEvent event) {
				History rowData = table.getSelectionModel().getSelectedItem();
				if (event.getCode().equals(KeyCode.ENTER)) {

					openSsh(rowData);

				}
				if (event.getCode().equals(KeyCode.DELETE)) {

					try {
						delete(rowData);
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}
		});

	}

	public void edit(History history) throws Exception {

		editPane ep = new editPane(history);

		// 创建新的stage
		Stage editStage = new Stage();
		try {
			editStage.getIcons().add(icon);

		} catch (Exception e) {
			// TODO: handle exception
			logger.debug(e.getMessage());
		}
		//保持前端
		editStage.initModality(Modality.APPLICATION_MODAL);

		editStage.setTitle("编辑主机");

		editStage.setScene(new Scene(ep.GetAddPane(), 410, 550));

		editStage.showAndWait();

		refersh();

		// */
	}

	public void add() throws Exception {
		// 创建新的stage
		Stage addStage = new Stage();
		try {
			addStage.getIcons().add(icon);

		} catch (Exception e) {
			// TODO: handle exception
			logger.debug(e.getMessage());
		}
		//保持前端
		addStage.initModality(Modality.APPLICATION_MODAL);
		addStage.setTitle("添加主机");
		addPane ap = new addPane();
		addStage.setScene(new Scene(ap.GetAddPane(), 410, 550));
		addStage.showAndWait();
		refersh();
	}

	public void delete(History history) throws ClassNotFoundException, SQLException {

		SqliteUtil sq = new SqliteUtil();
		sq.del("history", history.getId());

		refersh();
	}

	public void openSsh(History history) {

		// TODO Auto-generated method stub

		TerminalConfig darkConfig = new TerminalConfig();
		darkConfig.setBackgroundColor(Color.rgb(16, 16, 16));
		darkConfig.setForegroundColor(Color.rgb(240, 240, 240));
		darkConfig.setCursorColor(Color.rgb(255, 0, 0, 0.5));
		darkConfig.setHostname(history.getIp());
		darkConfig.setPort(history.getPort());
		darkConfig.setUsername(history.getUsername());
		darkConfig.setPassword(history.getPassword());

		darkConfig.setPemFile(history.getPkey());

		darkConfig.setProxyType(history.getProxyType());
		darkConfig.setProxyIp(history.getProxyIp());
		darkConfig.setProxyPort(history.getProxyPort());
		darkConfig.setProxyUser(history.getProxyUser());
		darkConfig.setProxyPassword(history.getProxyPassword());

		try {
			TerminalBuilder terminalBuilder = new TerminalBuilder(darkConfig);
			BorderPane pane = new BorderPane();
			TerminalTab terminal = terminalBuilder.newTerminal(pane);
			terminal.setText("✺"+history.getName());
			terminal.setId("" + history.getId());

			mtabs.getTabs().add(terminal);
			mtabs.getSelectionModel().select(terminal);// 默认选中

			//
			// 非空白处菜单
			ContextMenu cm = new ContextMenu();
			MenuItem down = new MenuItem("下载");
			// MenuItem copy = new MenuItem("复制");

			cm.getItems().addAll(down);

			terminal.getTerminal().addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

				@Override
				public void handle(MouseEvent t) {

					if (t.getButton() == MouseButton.SECONDARY) {
						cm.show(terminal.getTerminal(), t.getScreenX(), t.getScreenY());

						down.setOnAction(new EventHandler<ActionEvent>() {

							@Override
							public void handle(ActionEvent event) {

								ProgressBar pbar = terminal.getBar();

								ThreadHelper.start(() -> {

									ThreadHelper.runActionLater(() -> {
										pbar.setManaged(true);
										pbar.setVisible(true);
									});
									ThreadHelper.runActionLater(() -> {
										// File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
										// String desktopPath = desktopDir.getAbsolutePath();
										final DirectoryChooser dirChooser = new DirectoryChooser();
										File file = dirChooser.showDialog(new Stage());
										if (file != null) {
											ThreadHelper.start(() -> {
												ThreadHelper.runActionLater(() -> {
													// TODO Auto-generated method stub
													String ff = terminal.getTerminal().getSelect();
													String pp = terminal.getTerminal().getPwd();
													try {
														JschTools expc = new JschTools(history);

														PFile fileinfo = expc.getFileInfo(pp + "/" + ff, ff);

														expc.getfile(fileinfo.isDir(), pp, ff, file.getPath(), pbar,
																terminal.getsysteminfo());

													} catch (JSchException e) {
														// TODO Auto-generated catch block
														terminal.setInfoText("下载失败：" + e.getMessage(), (long) 5000);
														e.printStackTrace();
													} catch (SftpException e) {
														// TODO Auto-generated catch block

														terminal.setInfoText("下载失败：" + e.getMessage(), (long) 5000);

														e.printStackTrace();
													} catch (IOException e) {
														// TODO Auto-generated catch block
														terminal.setInfoText("下载失败：" + e.getMessage(), (long) 5000);
														e.printStackTrace();
													}

												});

											});
										}
									});

								});

							}
						});

					}
					if (t.getButton() == MouseButton.MIDDLE || t.getButton() == MouseButton.PRIMARY) {

						if (cm.isShowing()) {
							cm.hide();

						}

					}
				}

			});

			// 直接上传在黑色界面
			terminal.getTerminal().setOnDragDetected(new EventHandler<MouseEvent>() {
				@Override
				public void handle(MouseEvent event) {
					Dragboard db = pane.startDragAndDrop(TransferMode.ANY);
					ClipboardContent content = new ClipboardContent();
					db.setContent(content);
					event.consume();
				}
			});
			terminal.getTerminal().setOnDragOver(new EventHandler<DragEvent>() {

				@Override
				public void handle(DragEvent event) {
					event.acceptTransferModes(TransferMode.ANY);
					event.consume(); //

				}
			});

			terminal.getTerminal().setOnDragExited(new EventHandler<DragEvent>() {
				@Override
				public void handle(DragEvent event) {

					Dragboard dragboard = event.getDragboard();
					List<java.io.File> files = dragboard.getFiles();
					String path = terminal.getTerminal().getPwd();
					ProgressBar pbar = terminal.getBar();
					if (files.size() > 0) {

						ThreadHelper.start(() -> {
							ThreadHelper.runActionLater(() -> {
								pbar.setVisible(true);
								pbar.setManaged(true);

							});
							ThreadHelper.start(() -> {
							for (File file : files) {
									ThreadHelper.runActionLater(() -> {
										try {
											JschTools exp = new JschTools(history);
											exp.putfile(file, path, pbar, terminal.getsysteminfo());
										} catch (JSchException e) {
											// TODO Auto-generated catch block
											terminal.setInfoText("上传失败：" + e.getMessage(), (long) 5000);

											e.printStackTrace();
										} catch (FileNotFoundException e) {
											// TODO Auto-generated catch block
											terminal.setInfoText("上传失败：" + e.getMessage(), (long) 5000);

											e.printStackTrace();
										} catch (SftpException e) {
											// TODO Auto-generated catch block
											terminal.setInfoText("上传失败：" + e.getMessage(), (long) 5000);

											e.printStackTrace();

										}
									});
								

								}
							});
						});

					}

				}
			});

		} catch (Exception e) {
			// TODO: handle exception

			Alert alert = new Alert(AlertType.CONFIRMATION);
			alert.setTitle("消息提示");
			alert.setHeaderText(null);
			alert.setContentText("链接出错" + e.getMessage());

			Optional<ButtonType> result = alert.showAndWait();
			if (result.get() == ButtonType.OK) {
				// ... user chose OK
				System.out.println("确定");
			} else {
				// ... user chose CANCEL or closed the dialog
				System.out.println("取消");
			}

			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		launch(args);
		// logger.debug("开始启动");
	}
}
